library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;


package mypackage is 
function complementary(r2,r1:unsigned) return unsigned;
end package mypackage;


package body mypackage is
function complementary(r2,r1:unsigned) return unsigned is
	variable max,min:unsigned(r2'length-1 downto 0); --10 bit
	variable max_tmp,max_tmpdiv,min_tmp,r_sum:unsigned(r2'length+1 downto 0);
	variable dox2,realsum,max9,min9,er_tmp:unsigned(r2'length downto 0);
	variable do,er:unsigned(r2'length-1 downto 0);
	variable result:unsigned((r2'length)*2-1 downto 0);
	begin
		if r2 > r1 then  
			max := r2;min := r1;
		else
			min := r2;max := r1;
		end if;
		
		max_tmp := max&"00";
		max_tmpdiv := "00"&max;
		min_tmp := "00"&min;
		r_sum := (max_tmp-max_tmpdiv)+min_tmp;
		
		if r_sum(1) = '1' then 
			do := r_sum(r_sum'length-1 downto 2)+1;
		else
			do := r_sum(r_sum'length-1 downto 2);
		end if;
		
		dox2 := do&'0';
		max9 := '0'&max;
		min9 := '0'&min;
		realsum := max9 + min9;
		
		if realsum > dox2 then
			er_tmp := realsum - dox2;
			er(er'length-1):='0';
			er(er'length-2 downto 0) := er_tmp(r2'length-2 downto 0);
		else
			er_tmp := dox2 - realsum;
			er(er'length-1):='0';
			er(er'length-2 downto 0) := er_tmp(r2'length-2 downto 0);	
			er := (er xor "11111111") + 1;
		end if;
		
		result := do&er;
	return result;
end function complementary;
end package body mypackage;